package com.jandar.spider.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jandar.spider.config.property.SpiderConfig;
//import com.jandar.spider.enums.PunishAreaEnum;
import com.jandar.spider.mapper.PunishStatisticsMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalField;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class PunishStatisticsService {
    @Autowired
    private PunishStatisticsMapper punishStatisticsMapper;

    @Autowired
    private SpiderConfig spiderConfig;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public ResponseEntity<Map<String, Object>> checkData() {
        Map<String, Object> map = new HashMap<>();
        long max = punishStatisticsMapper.getMaxPunishTimeByArea("浙江省杭州市拱墅区").toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long time = 5 * 24 * 60 * 60 * 1000;
        long now = System.currentTimeMillis();
        String newDatePunishTime = simpleDateFormat.format(new Date(max));
        int count = getCount();
        int repeatCount = getRepeatCount();
        StringBuilder message = new StringBuilder();
        message.append("数据总量：").append(count).append("条").append(";");
        message.append("数据库重复数据：").append(repeatCount).append("条").append(";");
        message.append("最新数据发布日期： ").append(newDatePunishTime).append(";");
        if (now - time > max) {
            message.append("当前数据日期过旧");
            map.put("message", message.toString());
            return new ResponseEntity<>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (repeatCount > 0) {
            message.append("数据库有重复数据");
            map.put("message", message.toString());
            return new ResponseEntity<>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        map.put("message", message.toString());
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    public String getMaxPunishTimeByArea(String area) {
        LocalDateTime max = punishStatisticsMapper.getMaxPunishTimeByArea(area);
        if (max == null) {
            return null;
        }
        return max.format(DateTimeFormatter.BASIC_ISO_DATE);
    }

    public Integer getCount() {
        return punishStatisticsMapper.getCount();
    }

    public Integer getRepeatCount() {
        return punishStatisticsMapper.getRepeatCount();
    }

    public Integer getCountByArea(String area) {
        return punishStatisticsMapper.getCountByArea(area);
    }

    public void sendEmailByArea(String area) {
        if (!spiderConfig.getSpider().getSendEmail()) {
            return;
        }
        OkHttpClient client = new OkHttpClient();

        String maxPunishTime = getMaxPunishTimeByArea(area);
        Integer count = getCountByArea(area);
        FormBody.Builder form = new FormBody.Builder();
        form.add("subject", area + "数据监控");
        form.add("content", "最新数据发布日期：" + maxPunishTime + "<br> \n 数据总量：" + count);
        form.add("to", "陈龙:1838189006@qq.com");
        form.add("fromName", "jandar");

        Request request = new Request.Builder()
                .url("http://172.16.137.55:8081/email-service/sendMail/send")
                .post(form.build())
                .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}